package it.unibo.refolding.pico.mfp;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Objects;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.google.common.base.Preconditions;

public class ByteOrderAndVersion {
  final ByteOrder byteOrder;
  final byte version;
  
  public ByteOrderAndVersion(ByteOrder byteOrder, byte version) {
    this.byteOrder = byteOrder;
    this.version = version;
  }
  
  public ByteOrder byteOrder() {
    return byteOrder;
  }
  
  public static int byteCount() {
    return 2;
  }
  
  public short unsignedChecksum() {
    return (short) (version & 0xFF);
  }
  
  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof ByteOrderAndVersion)) {
      return false;
    }
    ByteOrderAndVersion other = (ByteOrderAndVersion) obj;
    return byteOrder == other.byteOrder & version == other.version;
  }
  
  @Override
  public int hashCode() {
    return Objects.hash(byteOrder, version);
  }

  @Override
  public String toString() {
    return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
  }

  static ByteOrderAndVersion read(ByteBuffer bb) {
    byte version0 = bb.get();
    byte version1 = bb.get();
    final ByteOrder byteOrder;
    final byte version;
    if (version0 == 0) {
      byteOrder = ByteOrder.BIG_ENDIAN;
      version = version1;
    } else {
      Preconditions.checkArgument(version1 == 0, version1);
      byteOrder = ByteOrder.LITTLE_ENDIAN;
      version = version0;
    }
    return new ByteOrderAndVersion(byteOrder, version);
  }
}
